<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="60%" class="receivable-form-dialog">
    <div class="dialog-content">
      <!-- 头部区域 -->
      <div class="dialog-header">
        <div class="header-icon">
          <Icon icon="ep:money" />
        </div>
        <div class="header-content">
          <h3 class="dialog-title">{{ dialogTitle }}</h3>
          <p class="dialog-subtitle">配置回款基本信息</p>
        </div>
      </div>

      <!-- 表单区域 -->
      <div class="form-container">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          class="enhanced-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:document" class="section-icon" />
              <span class="section-title">基本信息</span>
            </div>

            <div class="form-grid">
              <el-form-item label="回款编号" prop="no" class="form-item">
                <div class="input-wrapper">
                  <Icon icon="ep:document-copy" class="input-icon" />
                  <el-input
                    disabled
                    v-model="formData.no"
                    placeholder="保存时自动生成"
                    class="enhanced-input disabled-input"
                  />
                </div>
              </el-form-item>

              <el-form-item label="负责人" prop="ownerUserId" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:user" class="select-icon" />
                  <el-select
                    filterable
                    v-model="formData.ownerUserId"
                    :disabled="formType !== 'create'"
                    class="enhanced-select"
                    placeholder="请选择负责人"
                  >
                    <el-option
                      v-for="item in userOptions"
                      :key="item.id"
                      :label="item.nickname"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 客户和合同信息 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:office-building" class="section-icon" />
              <span class="section-title">客户和合同信息</span>
            </div>

            <div class="form-grid">
              <el-form-item label="客户名称" prop="customerId" class="form-item">
                <div class="select-wrapper">
                  <el-select-v2
                    v-model="formData.customerId"
                    :options="customerList"
                    :disabled="formType !== 'create'"
                    filterable
                    :props="{
                      value: 'id',
                      label: 'name'
                    }"
                    clearable
                    placeholder="请选择客户"
                    class="enhanced-select-v2"
                    @change="handleCustomerChange"
                  />
                </div>
              </el-form-item>

              <el-form-item label="合同名称" prop="contractId" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:document" class="select-icon" />
                  <el-select
                    v-model="formData.contractId"
                    :disabled="formType !== 'create' || !formData.customerId"
                    class="enhanced-select"
                    filterable
                    @change="handleContractChange"
                    placeholder="请选择合同"
                  >
                    <el-option
                      v-for="data in contractList"
                      :key="data.id"
                      :label="data.name"
                      :value="data.id!"
                      :disabled="data.auditStatus !== 20"
                    />
                  </el-select>
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 回款信息 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:money" class="section-icon" />
              <span class="section-title">回款信息</span>
            </div>

            <div class="form-grid">
              <el-form-item label="回款期数" prop="planId" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:list" class="select-icon" />
                  <el-select
                    v-model="formData.planId"
                    :disabled="formType !== 'create' || !formData.contractId"
                    class="enhanced-select"
                    @change="handleReceivablePlanChange"
                    placeholder="请选择回款期数"
                  >
                    <el-option
                      v-for="data in receivablePlanList"
                      :key="data.id"
                      :label="'第 ' + data.period + ' 期'"
                      :value="data.id!"
                      :disabled="data.receivableId"
                    />
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="回款方式" prop="returnType" class="form-item">
                <div class="select-wrapper">
                  <Icon icon="ep:credit-card" class="select-icon" />
                  <el-select
                    v-model="formData.returnType"
                    class="enhanced-select"
                    placeholder="请选择回款方式"
                  >
                    <el-option
                      v-for="dict in getIntDictOptions(DICT_TYPE.CRM_RECEIVABLE_RETURN_TYPE)"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item label="回款金额" prop="price" class="form-item">
                <div class="price-wrapper">
                  <Icon icon="ep:money" class="price-icon" />
                  <el-input-number
                    v-model="formData.price"
                    class="enhanced-number"
                    controls-position="right"
                    placeholder="请输入回款金额"
                    :min="0.01"
                    :precision="2"
                  />
                  <span class="price-unit">元</span>
                </div>
              </el-form-item>

              <el-form-item label="回款日期" prop="returnTime" class="form-item">
                <div class="date-wrapper">
                  <Icon icon="ep:calendar" class="date-icon" />
                  <el-date-picker
                    v-model="formData.returnTime"
                    placeholder="选择回款日期"
                    type="date"
                    value-format="x"
                    class="enhanced-date-picker"
                  />
                </div>
              </el-form-item>
            </div>
          </div>

          <!-- 备注信息 -->
          <div class="form-section">
            <div class="section-header">
              <Icon icon="ep:edit" class="section-icon" />
              <span class="section-title">备注信息</span>
            </div>

            <div class="form-grid full-width">
              <el-form-item label="备注" prop="remark" class="form-item textarea-item">
                <div class="textarea-wrapper">
                  <Icon icon="ep:document" class="textarea-icon" />
                  <el-input
                    v-model="formData.remark"
                    placeholder="请输入备注"
                    type="textarea"
                    class="enhanced-textarea"
                    :rows="4"
                  />
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button :disabled="formLoading" type="primary" @click="submitForm" class="confirm-btn">
          <Icon icon="ep:check" class="btn-icon" />
          确定
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as ReceivablePlanApi from '@/api/crm/receivable/plan'
import * as ReceivableApi from '@/api/crm/receivable'
import * as UserApi from '@/api/system/user'
import * as CustomerApi from '@/api/crm/customer'
import * as ContractApi from '@/api/crm/contract'
import { useUserStore } from '@/store/modules/user'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import form from '@/components/Form/src/Form.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<ReceivableApi.ReceivableVO>({} as ReceivableApi.ReceivableVO)
const formRules = reactive({
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  contractId: [{ required: true, message: '合同不能为空', trigger: 'blur' }],
  returnTime: [{ required: true, message: '回款日期不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '回款金额不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表
const contractList = ref<ContractApi.ContractVO[]>([]) // 合同列表
const receivablePlanList = ref<ReceivablePlanApi.ReceivablePlanVO[]>([]) // 回款计划列表

/** 打开弹窗 */
const open = async (
  type: string,
  id?: number,
  receivablePlan?: ReceivablePlanApi.ReceivablePlanVO
) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ReceivableApi.getReceivable(id)
      await handleCustomerChange(formData.value.customerId)
      formData.value.contractId = formData.value.contract.id
    } finally {
      formLoading.value = false
    }
  }
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
  }
  // 从回款计划创建回款
  if (receivablePlan) {
    formData.value.customerId = receivablePlan.customerId
    await handleCustomerChange(receivablePlan.customerId)
    formData.value.contractId = receivablePlan.contractId
    await handleContractChange(receivablePlan.contractId)
    if (receivablePlan.id) {
      formData.value.planId = receivablePlan.id
      formData.value.price = receivablePlan.price
      formData.value.returnType = receivablePlan.returnType
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ReceivableApi.ReceivableVO
    if (formType.value === 'create') {
      await ReceivableApi.createReceivable(data)
      message.success(t('common.createSuccess'))
    } else {
      await ReceivableApi.updateReceivable(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {} as ReceivableApi.ReceivableVO
  formRef.value?.resetFields()
}

/** 处理切换客户 */
const handleCustomerChange = async (customerId: number) => {
  // 重置合同编号
  formData.value.contractId = undefined
  // 获得合同列表
  if (customerId) {
    contractList.value = []
    contractList.value = await ContractApi.getContractSimpleList(customerId)
  }
}

/** 处理切换合同 */
const handleContractChange = async (contractId: number) => {
  // 重置回款计划编号
  formData.value.planId = undefined
  if (contractId) {
    // 获得回款计划列表
    receivablePlanList.value = []
    receivablePlanList.value = await ReceivablePlanApi.getReceivablePlanSimpleList(
      formData.value.customerId,
      contractId
    )
    // 设置金额
    const contract = contractList.value.find((item) => item.id === contractId)
    if (contract) {
      formData.value.price = contract.totalPrice - contract.totalReceivablePrice
    }
  }
}

/** 处理切换回款计划 */
const handleReceivablePlanChange = (planId: number) => {
  if (!planId) {
    return
  }
  const receivablePlan = receivablePlanList.value.find((item) => item.id === planId)
  if (!receivablePlan) {
    return
  }
  formData.value.price = receivablePlan.price
  formData.value.returnType = receivablePlan.returnType
}
</script>

<style lang="scss" scoped>
.receivable-form-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;

    @media (max-width: 768px) {
      width: 95% !important;
      margin: 20px auto;
      max-height: 90vh;
    }
  }

  :deep(.el-dialog__header) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    max-height: 80vh;
    overflow-y: auto;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
    border-top: 1px solid #e5e7eb;
  }
}

.dialog-content {
  background: #f8fafc;
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  color: white;
  border-radius: 10px;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;

  @media (max-width: 768px) {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

.header-content {
  flex: 1;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.dialog-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

/* 表单容器 */
.form-container {
  background: white;
  padding: 24px;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

.enhanced-form {
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #374151;
    font-size: 14px;

    @media (max-width: 768px) {
      font-size: 13px;
    }
  }
}

/* 表单区域 */
.form-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;

  @media (max-width: 768px) {
    margin-bottom: 16px;
    padding: 16px;
  }
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #0052cc;
}

.section-icon {
  color: #0052cc;
  font-size: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

/* 表单网格 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  &.full-width {
    grid-template-columns: 1fr;
  }
}

.form-item {
  margin-bottom: 0;

  &.textarea-item {
    grid-column: 1 / -1;
  }
}

/* 输入框样式 */
.input-wrapper,
.select-wrapper,
.date-wrapper,
.textarea-wrapper,
.price-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}

.input-icon,
.select-icon,
.date-icon,
.textarea-icon,
.price-icon {
  position: absolute;
  left: 12px;
  color: #6b7280;
  font-size: 16px;
  z-index: 1;
}

.textarea-icon {
  top: 12px;
}

.enhanced-input,
.enhanced-select,
.enhanced-select-v2,
.enhanced-date-picker,
.enhanced-textarea,
.enhanced-number {
  width: 100%;

  :deep(.el-input__wrapper) {
    padding-left: 40px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    min-height: 40px;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }

  :deep(.el-input__inner) {
    font-size: 14px;

    @media (max-width: 768px) {
      font-size: 16px; // 防止iOS缩放
    }
  }

  :deep(.el-input__suffix) {
    right: 12px;
  }
}

.enhanced-textarea {
  :deep(.el-textarea__inner) {
    padding-left: 40px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;
    resize: vertical;
    min-height: 100px;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &:focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

/* 禁用输入框样式 */
.disabled-input {
  :deep(.el-input__wrapper) {
    background: #f3f4f6;
    border-color: #e5e7eb;

    .el-input__inner {
      color: #9ca3af;
      cursor: not-allowed;
    }
  }
}

/* 价格输入框 */
.price-wrapper {
  .price-unit {
    position: absolute;
    right: 12px;
    color: #6b7280;
    font-size: 14px;
    font-weight: 500;
    z-index: 1;
  }

  .enhanced-number {
    :deep(.el-input__wrapper) {
      padding-right: 40px;
      background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
      border: 2px solid #f59e0b;
    }

    :deep(.el-input__inner) {
      color: #92400e;
      font-weight: 600;
      font-size: 16px;
    }

    :deep(.el-input-number__increase),
    :deep(.el-input-number__decrease) {
      background: rgba(245, 158, 11, 0.1);
      border-color: #f59e0b;
      color: #92400e;

      &:hover {
        background: rgba(245, 158, 11, 0.2);
      }
    }
  }
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: white;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    gap: 8px;
  }
}

.cancel-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  background: white;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.2s ease;
  min-height: 40px;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  @media (max-width: 768px) {
    width: 100%;
    order: 2;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.confirm-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  color: white;
  transition: all 0.2s ease;
  min-height: 40px;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  @media (max-width: 768px) {
    width: 100%;
    order: 1;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

:deep(.el-loading-spinner) {
  .circular {
    width: 32px;
    height: 32px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dialog-content {
    background: #1f2937;
  }

  .form-container {
    background: #374151;
  }

  .form-section {
    background: #4b5563;
    border-color: #6b7280;
  }

  .section-title {
    color: #f9fafb;
  }

  .section-header {
    border-color: #60a5fa;
  }

  .section-icon {
    color: #60a5fa;
  }

  .enhanced-input,
  .enhanced-select,
  .enhanced-select-v2,
  .enhanced-date-picker,
  .enhanced-number {
    :deep(.el-input__wrapper) {
      background: #4b5563;
      border-color: #6b7280;

      .el-input__inner {
        color: #f9fafb;
      }
    }
  }

  .enhanced-textarea {
    :deep(.el-textarea__inner) {
      background: #4b5563;
      border-color: #6b7280;
      color: #f9fafb;
    }
  }

  .disabled-input {
    :deep(.el-input__wrapper) {
      background: #374151;
      border-color: #4b5563;

      .el-input__inner {
        color: #6b7280;
      }
    }
  }

  .input-icon,
  .select-icon,
  .date-icon,
  .textarea-icon,
  .price-icon {
    color: #d1d5db;
  }

  .price-unit {
    color: #d1d5db;
  }

  .price-wrapper {
    .enhanced-number {
      :deep(.el-input__wrapper) {
        background: linear-gradient(135deg, #92400e 0%, #b45309 100%);
        border-color: #f59e0b;
      }

      :deep(.el-input__inner) {
        color: #fbbf24;
      }

      :deep(.el-input-number__increase),
      :deep(.el-input-number__decrease) {
        background: rgba(251, 191, 36, 0.1);
        border-color: #f59e0b;
        color: #fbbf24;

        &:hover {
          background: rgba(251, 191, 36, 0.2);
        }
      }
    }
  }

  .dialog-footer {
    background: #374151;
  }

  .enhanced-form {
    :deep(.el-form-item__label) {
      color: #f9fafb;
    }
  }

  :deep(.el-loading-mask) {
    background: rgba(55, 65, 81, 0.9);
  }
}

/* 高对比度模式适配 */
@media (prefers-contrast: high) {
  .enhanced-input,
  .enhanced-select,
  .enhanced-select-v2,
  .enhanced-date-picker,
  .enhanced-number {
    :deep(.el-input__wrapper) {
      border: 2px solid #0052cc;
      box-shadow: none;

      &:hover,
      &.is-focus {
        border-color: #1d4ed8;
        box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.2);
      }
    }
  }

  .enhanced-textarea {
    :deep(.el-textarea__inner) {
      border: 2px solid #0052cc;
      box-shadow: none;

      &:hover,
      &:focus {
        border-color: #1d4ed8;
        box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.2);
      }
    }
  }

  .cancel-btn {
    border: 2px solid #6b7280;
  }

  .confirm-btn {
    background: #0052cc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
}

/* 减少动画模式适配 */
@media (prefers-reduced-motion: reduce) {
  .enhanced-input,
  .enhanced-select,
  .enhanced-select-v2,
  .enhanced-date-picker,
  .enhanced-textarea,
  .enhanced-number,
  .cancel-btn,
  .confirm-btn {
    transition: none;
  }

  .confirm-btn {
    &:hover {
      transform: none;
    }
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .enhanced-input,
  .enhanced-select,
  .enhanced-select-v2,
  .enhanced-date-picker,
  .enhanced-number {
    :deep(.el-input__wrapper) {
      min-height: 44px;
    }
  }

  .cancel-btn,
  .confirm-btn {
    min-height: 44px;
    padding: 12px 20px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .dialog-header {
    padding: 12px;
  }

  .form-container {
    padding: 12px;
  }

  .form-section {
    padding: 12px;
    margin-bottom: 12px;
  }

  .dialog-footer {
    padding: 12px;
  }

  .form-grid {
    gap: 12px;
  }
}

/* 横屏模式适配 */
@media (max-width: 768px) and (orientation: landscape) {
  .dialog-header {
    padding: 12px 16px;
    flex-direction: row;
    text-align: left;
  }

  .form-container {
    padding: 16px;
  }

  .form-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;

    &.full-width {
      grid-template-columns: 1fr;
    }
  }

  .textarea-item {
    grid-column: 1 / -1;
  }
}

/* 滚动条样式 */
.scroller {
  height: 200px;
  overflow-y: auto;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;

    &:hover {
      background: #94a3b8;
    }
  }
}
</style>
